'''
飞机大战 v0.1
'''
import turtle
from turtle import *
import random
import math

turtle.screensize(600, 600)
turtle.hideturtle()
turtle.tracer(0)


def drawMyPlane(x, y):
    """
    给出一个飞机底部中心的坐标，画一个三角形的飞机
    :param x: 坐标X
    :param y: 坐标Y
    :return:
    """
    plane_width = 20
    turtle.penup()
    turtle.setposition(x - plane_width / 2, y)
    pendown()
    turtle.setposition(x + plane_width / 2, y)
    turtle.setposition(x, y + plane_width)
    turtle.setposition(x - plane_width / 2, y)
    penup()


def keyLeft():
    """
    按左键，飞机向左
    :return:
    """
    global plane_x
    plane_x = plane_x - 10


def keyRight():
    """
    按右键，飞机向右
    :return:
    """
    global plane_x
    plane_x = plane_x + 10


def drawEnemyPlane(x, y):
    """
    在给定坐标为敌机底部的中间，画一个敌机，
    :param x:
    :param y:
    :return:
    """
    plane_width = 20
    turtle.penup()
    turtle.setposition(x - plane_width / 2, y)
    pendown()
    begin_fill()
    turtle.setposition(x + plane_width / 2, y)
    turtle.setposition(x, y - plane_width)
    turtle.setposition(x - plane_width / 2, y)
    end_fill()
    penup()


def enemyPlaneMove():
    """
    敌机的移动
    :return:
    """
    global enemy_planes
    for enemy_plane in enemy_planes:
        enemy_plane_x = enemy_plane[0]
        enemy_plane_y = enemy_plane[1]
        drawEnemyPlane(enemy_plane_x, enemy_plane_y)
        enemy_plane[1] = enemy_plane_y - 5


def enemyPlaneRemove():
    global enemy_planes
    for enemy_plane in enemy_planes:
        enemy_plane_x = enemy_plane[0]
        enemy_plane_y = enemy_plane[1]
        if (enemy_plane_x > 300) or \
                (enemy_plane_x < -300) or \
                (enemy_plane_y > 300) or \
                (enemy_plane_y < -300):
            enemy_planes.remove(enemy_plane)


def genEnemyPlane():
    """
    判断是否生成新敌机，如果可以，生成新敌机的新坐标
    :return:
    """
    global enemy_planes
    if len(enemy_planes) > 10:
        ''' 敌人太多，不生成 '''
        return

    gen_flag = random.random()
    gen_x = 0
    if gen_flag < 0.5:
        return
    else:
        gen_x = random.randint(-200, 200)

    for enemy_plane in enemy_planes:
        ''' 敌人飞机间水平与垂直距离太近，不生成 '''
        if (300 - enemy_plane[1]) < 50:
            return
        if abs(gen_x - enemy_plane[1]) < 50:
            return

    enemy_planes.append([gen_x, 300])


def drawScreen():
    """
    屏幕定时器的执行方法，画整个屏幕
    :return:
    """
    global plane_x
    global plane_y
    global enemy_planes
    turtle.clear()
    drawMyPlane(plane_x, plane_y)
    enemyPlaneRemove()
    genEnemyPlane()
    enemyPlaneMove()
    turtle.update()
    turtle.ontimer(drawScreen(), 200)


plane_x = 0
plane_y = -300
enemy_planes = [[0, 300], [-50, 300]]
turtle.listen()
turtle.onkeypress(keyLeft, "Left")
turtle.onkeypress(keyRight, "Right")
turtle.ontimer(drawScreen, 200)

turtle.mainloop()
